package com.clh.seckill.config;

import com.clh.seckill.pojo.User;
import org.springframework.core.MethodParameter;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

import javax.servlet.http.HttpServletRequest;

/**
 * @Author cailinhu
 * @Description 参数拦截器
 * @Date 2021-11-11 15:41
 * @Version 1.0
 */
@Component
public class UserHandlerArgumentResolver implements HandlerMethodArgumentResolver {
    /**
     * 指定参数拦截--》有这个参数才进行拦截
     * @param methodParameter
     * @return
     */
    @Override
    public boolean supportsParameter(MethodParameter methodParameter) {
        Class<?> parameterType = methodParameter.getParameterType();
        return parameterType == User.class;
    }

    /***
     * 拦截后要做的操作
     * @param methodParameter
     * @param modelAndViewContainer
     * @param nativeWebRequest
     * @param webDataBinderFactory
     * @return
     * @throws Exception
     */
    @Override
    public Object resolveArgument(MethodParameter methodParameter, ModelAndViewContainer modelAndViewContainer,
              NativeWebRequest nativeWebRequest, WebDataBinderFactory webDataBinderFactory) throws Exception {
        //将拦截器认证成功的user作为参数返回出去
//        HttpServletRequest request = nativeWebRequest.getNativeRequest(HttpServletRequest.class);
//        return request.getAttribute("user");
        User user = UserContext.getUser();
        return user;
    }
}
